package com.micangcaihang.micang.mvp.task.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.micangcaihang.common.base.fragment.BaseFragment;
import com.micangcaihang.common.utils.Properties;
import com.micangcaihang.common.utils.StringUtils;
import com.micangcaihang.common.utils.TimeUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.databinding.FragmentTaskLoansInfoFBinding;
import com.micangcaihang.micang.entity.FTaskLoansInfoEntity;
import com.micangcaihang.micang.entity.PickerEntity;
import com.micangcaihang.micang.http.request.FTaskLoansInfoRequest;
import com.micangcaihang.micang.mvp.task.contract.FTaskLoansInfoContract;
import com.micangcaihang.micang.mvp.task.presenter.FTaskLoansInfoPresenter;
import com.micangcaihang.micang.view.PickerViewHelper;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * <pre>
 *     author : Fandy
 *     e-mail : fandayongfly@gmail.com
 *     time   : 2017/07/24
 *     update : 2017/07/24
 *     desc   : 风控 贷款信息
 *     version: 1.0
 * </pre>
 */

public class FTaskLoansInfoFragment extends BaseFragment<FTaskLoansInfoPresenter,
        FragmentTaskLoansInfoFBinding> implements FTaskLoansInfoContract.View {
    private String id;
    private FTaskLoansInfoRequest mRequest;
    private FTaskLoansInfoRequest mOldRequest;
    private int pickerType;
    private boolean isNetSuccess;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getArguments().getString("id");
    }

    public static FTaskLoansInfoFragment newInstance(String id) {
        Bundle args = new Bundle();
        FTaskLoansInfoFragment fragment = new FTaskLoansInfoFragment();
        args.putString("id", id);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 获取资源文件布局
     *
     * @return 资源布局文件layout
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_loans_info_f;
    }

    @Override
    protected void initData() {
        super.initData();
        mRequest = new FTaskLoansInfoRequest();
        mRequest.setId(id);
        mOldRequest = new FTaskLoansInfoRequest();
        mOldRequest.setId(id);
    }

    @Override
    public void initPresenter() {
        super.initPresenter();
        mPresenter.setId(id);
    }

    /**
     * 初始化按钮监听
     */
    @Override
    protected void initListener() {
        mViewBinding.setClickHandler(new FTaskLoansInfoFragment.ClickHandler());
    }

    /**
     * 返回下拉框信息
     *
     * @param list
     * @param type
     */
    @Override
    public void returnPickerViewData(List<PickerEntity> list, String type) {
        switch (pickerType) {
            case 1:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getIs_provident(), list,
                        pickerEntity1 -> {
                            mRequest.setIs_provident(pickerEntity1.getSign_id());
                            mViewBinding.tvIsProvident.setText(pickerEntity1.getTitle());
                        });
                break;
            case 2:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getLoaner_use(), list,
                        pickerEntity1 -> {
                            mRequest.setLoaner_use(pickerEntity1.getSign_id());
                            mViewBinding.tvLoanerUse.setText(pickerEntity1.getTitle());
                        });
                break;
            case 3:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getIs_lease(), list,
                        pickerEntity1 -> {
                            mRequest.setIs_lease(pickerEntity1.getSign_id());
                            mViewBinding.tvIsLease.setText(pickerEntity1.getTitle());
                        });
                break;
            case 4:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getBusiness_source(), list,
                        pickerEntity1 -> {
                            mRequest.setBusiness_source(pickerEntity1.getSign_id());
                            mViewBinding.tvBusinessSource.setText(pickerEntity1.getTitle());
                        });
                break;
            case 5:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getGuaranty_assets(), list,
                        pickerEntity1 -> {
                            mRequest.setGuaranty_assets(pickerEntity1.getSign_id());
                            mViewBinding.tvGuarantyAssets.setText(pickerEntity1.getTitle());
                        });
                break;
            case 6:
                PickerViewHelper.showOnePickerView(_mActivity, type, mRequest.getRisk_address(), list,
                        pickerEntity1 -> {
                            mRequest.setRisk_address(pickerEntity1.getSign_id());
                            mViewBinding.tvRiskAddress.setText(pickerEntity1.getTitle());
                        });
                break;
        }
    }

    /**
     * 返回贷款信息
     *
     * @param entity
     */
    @Override
    public void returnLoansInfoData(FTaskLoansInfoEntity entity) {
        isNetSuccess = true;
        String[] excludsArray = new String[]{"choose_list", "id"};
        try {
            Properties.copyPropertiesExclude(entity, mRequest, excludsArray);
            Properties.copyPropertiesExclude(entity, mOldRequest, excludsArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // //// 产权人
        if (!StringUtils.isEmpty(entity.getProperty_owner())) {
            mViewBinding.etPropertyOwner.setText(entity.getProperty_owner());
        }
        //借款人姓名
        if (!StringUtils.isEmpty(entity.getCustomer_name())) {
            mViewBinding.etLoanerName.setText(entity.getCustomer_name());
        }
        //借款时间开始
        //借款时间结束
        if (!StringUtils.isEmpty(entity.getLoan_date_start()) && !StringUtils.isEmpty(entity.getLoan_date_end())) {
            String start = TimeUtils.millis2StringDay(Long.parseLong(entity.getLoan_date_start()) * 1000);
            String end = TimeUtils.millis2StringDay(Long.parseLong(entity.getLoan_date_end()) * 1000);
            if (!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)) {
                mViewBinding.tvLoanDate.setText(start + " 至 " + end);
            }
        }
        //申请金额
        if (!StringUtils.isEmpty(entity.getApply_money())) {
            mViewBinding.etApplyMoney.setText(entity.getApply_money());
        }
        //担保数量
        if (!StringUtils.isEmpty(entity.getGuaranty_amount())) {
            mViewBinding.etGuarantyAmount.setText(entity.getGuaranty_amount());
        }
        //还款来源
        if (!StringUtils.isEmpty(entity.getRepay_source())) {
            mViewBinding.etRepaySource.setText(entity.getRepay_source());
        }
        //渠道放
        if (!StringUtils.isEmpty(entity.getChannel_name())) {
            mViewBinding.etChannelName.setText(entity.getChannel_name());
        }
        //实际借款金额
        if (!StringUtils.isEmpty(entity.getActual_money())) {
            mViewBinding.etActualMoney.setText(entity.getActual_money());
        }
        //房产证取得时间
        if (!StringUtils.isEmpty(entity.getGet_date())) {
            mViewBinding.tvGetDate.setText(TimeUtils.millis2StringDay(Long.parseLong(entity.getGet_date()) * 1000));
        }
        if (entity.getChoose_list() != null) {
            FTaskLoansInfoEntity.ChooseListBean chooseList = entity.getChoose_list();
            // // 是否使用公积金
            if (!StringUtils.isEmpty(chooseList.getIs_provident())) {
                mViewBinding.tvIsProvident.setText(chooseList.getIs_provident());
            }
            // // 是否使用公积金
            if (!StringUtils.isEmpty(chooseList.getIs_provident())) {
                mViewBinding.tvIsProvident.setText(chooseList.getIs_provident());
            }
            // //  租赁情况
            if (!StringUtils.isEmpty(chooseList.getIs_lease())) {
                mViewBinding.tvIsLease.setText(chooseList.getIs_lease());
            }
            //业务来源
            if (!StringUtils.isEmpty(chooseList.getBusiness_source())) {
                mViewBinding.tvBusinessSource.setText(chooseList.getBusiness_source());
            }
            //担保资产
            if (!StringUtils.isEmpty(chooseList.getGuaranty_assets())) {
                mViewBinding.tvGuarantyAssets.setText(chooseList.getGuaranty_assets());
            }
            //面审地点
            if (!StringUtils.isEmpty(chooseList.getRisk_address())) {
                mViewBinding.tvRiskAddress.setText(chooseList.getRisk_address());
            }
            mViewBinding.tvLoanerUse.setText(chooseList.getLoaner_use());
        }
    }

    public class ClickHandler {
        public void onShowLoandatePickerView(View view) {
            Calendar endData = Calendar.getInstance();//系统当前时间
            endData.set(2050, 0, 1);
            Calendar startData = Calendar.getInstance();
            startData.set(startData.get(Calendar.YEAR) - 1, startData.get(Calendar.MONTH), startData.get(Calendar.DAY_OF_MONTH));
            Calendar selectData = Calendar.getInstance();
            if (!StringUtils.isEmpty(mRequest.getLoan_date_start())) {
                selectData.setTime(TimeUtils.millis2Date(Long.parseLong(mRequest.getLoan_date_start()) * 1000));
            }
            PickerViewHelper.showYearMonthDayPicker(_mActivity, "借款开始时间", startData, endData, selectData, date -> {
                Calendar endData1 = Calendar.getInstance();//系统当前时间
                endData1.set(2050, 0, 1);
                Calendar selectData1 = Calendar.getInstance();
                if (!StringUtils.isEmpty(mRequest.getLoan_date_end())) {
                    selectData1.setTime(TimeUtils.millis2Date(Long.parseLong(mRequest.getLoan_date_end()) * 1000));
                }
                PickerViewHelper.showYearMonthDayPicker(_mActivity, "借款结束时间", selectData1, endData1, selectData1, date1 -> {
                    String startDate = String.valueOf(TimeUtils.date2Millis(date) / 1000);
                    mRequest.setLoan_date_start(startDate);
                    String endDate = String.valueOf(TimeUtils.date2Millis(date1) / 1000);
                    mRequest.setLoan_date_end(endDate);
                    mViewBinding.tvLoanDate.setText(TimeUtils.millis2StringDay(TimeUtils.date2Millis(date)) + " 至 " + TimeUtils.millis2StringDay(TimeUtils.date2Millis(date1)));
                });
            });
        }

        public void onShowIsProvidentPickerView(View view) {
            pickerType = 1;
            mPresenter.loadPickerViewData("li_boolean", "是否使用公积金");
        }

        public void onShowLoanerUsePickerView(View view) {
            pickerType = 2;
            mPresenter.loadPickerViewData("loaner_use", "借款用途");
        }

        public void onShowIsLeasePickerView(View view) {
            pickerType = 3;
            mPresenter.loadPickerViewData("is_lease", "租赁情况");
        }

        public void onShowGetDatePickerView(View view) {
            Calendar startDate = Calendar.getInstance();
            startDate.set(1955, 0, 1);
            Calendar endData = Calendar.getInstance();//系统当前时间
            Calendar selectData = Calendar.getInstance();
            if (!StringUtils.isEmpty(mRequest.getGet_date())) {
                selectData.setTime(TimeUtils.millis2Date(Long.parseLong(mRequest.getGet_date()) * 1000));
            }
            PickerViewHelper.showYearMonthDayPicker(_mActivity, "房产证取得时间", startDate, endData, selectData, new PickerViewHelper.OnTimeSelectListenner() {
                @Override
                public void onTimeSelect(Date date) {
                    String date2String = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()));
                    mViewBinding.tvGetDate.setText(date2String);
                    String checkin_date = String.valueOf(TimeUtils.string2Millis(date2String, new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())) / 1000);
                    mRequest.setGet_date(checkin_date);
                }
            });
        }

        public void onShowBusinessSourcePickerView(View view) {
            pickerType = 4;
            mPresenter.loadPickerViewData("business_source", "业务来源");
        }

        public void onShowGuarantyAssetsPickerView(View view) {
            pickerType = 5;
            mPresenter.loadPickerViewData("guaranty_assets", "担保资产");
        }

        public void onShowRiskAddressPickerView(View view) {
            pickerType = 6;
            mPresenter.loadPickerViewData("risk_address", "面审地点");
        }

        public void onSave(View view) {
            saveData();
        }
    }

    /**
     * 开始保存数据请求
     */
    public void saveData() {
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            ToastUtils.showLong("您没有更改任何信息，无需保存");
            return;
        }
        isNetSuccess = false;
        mPresenter.saveLoansInfo(mRequest);
    }

    /**
     * 判断是否保存过数据 没有的话点击保存去保存
     *
     * @return 是否保存当前页面数据
     */
    public boolean isSaveData() {
        //如果请求错误则返回true
        if (!isNetSuccess) {
            return true;
        }
        setSaveData();
        if (mRequest.toString().equals(mOldRequest.toString())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * s设置请求数据
     */
    private void setSaveData() {
        mRequest.setProperty_owner(mViewBinding.etPropertyOwner.getText().toString().trim());
        mRequest.setCustomer_name(mViewBinding.etLoanerName.getText().toString().trim());
        mRequest.setApply_money(mViewBinding.etApplyMoney.getText().toString().trim());
        mRequest.setGuaranty_amount(mViewBinding.etGuarantyAmount.getText().toString().trim());
        mRequest.setRepay_source(mViewBinding.etRepaySource.getText().toString().trim());
        mRequest.setChannel_name(mViewBinding.etChannelName.getText().toString().trim());
        mRequest.setActual_money(mViewBinding.etActualMoney.getText().toString().trim());
    }
}
